<template>
  <div ref="chartRef" class="myChart" />
</template>
<script lang="ts" setup>
  import { onMounted, PropType, shallowRef, toRefs, watch } from 'vue';
  import * as echarts from 'echarts/core';
  import { useCharts, ChartType } from './useCharts';

  defineOptions({
    name: 'VCharts',
  });
  const props = defineProps({
    type: {
      type: String as PropType<ChartType>,
      default: 'bar',
    },
    options: {
      type: Object as PropType<echarts.EChartsCoreOption>,
      default: () => ({}),
    },
  });
  const { type, options } = toRefs(props);
  const chartRef = shallowRef();
  const { charts, setOptions, initChart } = useCharts({ type, el: chartRef });
  onMounted(async () => {
    await initChart();
    setOptions(options.value);
  });
  watch(
    // 出于性能考虑，所有传入组件options的数据都要是shallowReactive类型，避免不必要的响应式转换
    options,
    () => {
      setOptions(options.value);
    },
    {
      deep: true,
    }
  );
  defineExpose({
    $charts: charts,
  });
</script>
<style lang="less" scoped></style>
